package cn.newgrand.netcall.integration.sms;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomClosingListener;
import org.jivesoftware.spark.ui.MessageEventListener;
import org.jivesoftware.spark.ui.rooms.ChatRoomImpl;
import org.jivesoftware.spark.util.log.Log;

import cn.newgrand.common.StringUtil;
import cn.newgrand.netcall.common.StringUtilCommon;
import cn.newgrand.netcall.integration.AppSysRes;
import cn.newgrand.netcall.integration.IntegrationManager;
import cn.newgrand.netcall.smackx.integration.AppSysOfflineDateIQ;

public class SendSMSDecorator implements ChatRoomClosingListener,MessageEventListener{
	
	private ChatRoomImpl chatRoomImpl;
	private JCheckBox sendSMSCheckBox;
	private SMS sms = new SMS();
	private SMSContact smsContactSender;
	private SMSContact smsContactReceiver;
	private long THREEHOUR = 3*60*60*1000;
	private long ONEHOUR = 1*60*60*1000;
	
	public SendSMSDecorator(ChatRoom chatRoom){
		this.chatRoomImpl = (ChatRoomImpl)chatRoom;
		Presence presence = chatRoomImpl.getPresence();
		sendSMSCheckBox = new JCheckBox("同时发送手机短信");
		sendSMSCheckBox.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String participantJid = chatRoomImpl.getParticipantJID();
				String phone = SparkManager.getVCardManager().getVCard(participantJid).getPhoneWork("CELL");
				if (StringUtil.isEmpty(phone)) {
					JOptionPane.showMessageDialog(chatRoomImpl,
							"接收者没有工作手机号码，\n必须填写工作手机号码后才能发送短信。",
							"消息", JOptionPane.INFORMATION_MESSAGE);
					sendSMSCheckBox.setSelected(false);
					return;
				}
			}
		});
		//1-用户有权限并且2-短信服务可用的时候还有在对应的3-发送对象是离开或者不在线的时候才添加"同时发送短信"的复选框
		if(SMSManager.isGrantSendSMS && SMSManager.isSMSServerAvailable){
			if(Presence.Type.unavailable == presence.getType() || Presence.Mode.xa == presence.getMode()){
				//final JLabel dividerLabel = new JLabel(SparkRes.getImageIcon("DIVIDER_IMAGE"));
		        //chatRoom.getEditorBar().add(dividerLabel);
				//chatRoomImpl.getEditorBar().add(sendSMSCheckBox);
			}
		}
		chatRoomImpl.addMessageEventListener(this);
	}

	@Override
	public void sendingMessage(final Message message) {
//		if(sendSMSCheckBox.isSelected()){}
		//1-发送者有发送权限  2-接收者必须填写了手机号码 3-接收者是离线3小时或者离开1小时
		setAwayOfflineTime();
		Presence presence = chatRoomImpl.getPresence();
		final String participantJid = chatRoomImpl.getParticipantJID();
		final String username = StringUtilCommon.parseName(participantJid);
		final String phone = SparkManager.getVCardManager().getVCard(participantJid).getPhoneWork("CELL");
		if(SMSManager.isGrantSendSMS && !StringUtil.isEmpty(phone)){
			//判断接收者是离线还是离开
			if(Presence.Type.unavailable == presence.getType()){
				//获取接受者离线的时间
				long offlineDate= getOfflineDate(participantJid);
				if(offlineDate >= THREEHOUR){
					//判断接收者离线的时间是否大于3小时.
					sendSMS(message,phone,participantJid);
				}else{
					//离线时间小于3小时.取得时间差定时发送
					Timer timer = new Timer();
					TimerTask task = new TimerTask() {
						@Override
						public void run() {
							//时间差到达的时候再次判断接收者的离线时间是否大于3小时(大于发短信.否则不处理)
							long offlineDate2 = getOfflineDate(participantJid);
							if(offlineDate2 >= THREEHOUR)
								sendSMS(message,phone,participantJid);
						}
					};
					timer.schedule(task, THREEHOUR-offlineDate);
				}
			}else if(Presence.Mode.xa == presence.getMode()){
				//获取接收者的离开时间
				long awayDate = SMSManager.awayDateMap.get(username);
				long awayedDate = System.currentTimeMillis() - awayDate;
				if(awayedDate >= ONEHOUR){
					sendSMS(message,phone,participantJid);
				}else{
					Timer timer = new Timer();
					TimerTask task = new TimerTask() {
						@Override
						public void run() {
							//再次取接收者离开的时间判断是否大于1小时(大于则发短信,否则不处理)
							if(SMSManager.awayDateMap.containsKey(username)){
								long awayDate2 = SMSManager.awayDateMap.get(username);
								long awayedDate2 = System.currentTimeMillis() - awayDate2;
								if(awayedDate2 >= ONEHOUR){
									sendSMS(message,phone,participantJid);
								}
							}
						}
					};
					timer.schedule(task, ONEHOUR-awayedDate);
				}
			}
		}
	}
	
	/**
	 * 获取接收的离线时间
	 * @param participantJid 接收者的id
	 * @return
	 */
	public long getOfflineDate(String participantJid){
		AppSysOfflineDateIQ offlineDateIQ = new AppSysOfflineDateIQ();
		offlineDateIQ.setType(IQ.Type.GET);
		offlineDateIQ.setReceiverJid(StringUtilCommon.parseName(participantJid));
		offlineDateIQ.setTo("integration." + SparkManager.getConnection().getServiceName());
		final PacketCollector collector = SparkManager.getConnection().createPacketCollector(new PacketIDFilter(offlineDateIQ.getPacketID()));
		SparkManager.getConnection().sendPacket(offlineDateIQ);
		AppSysOfflineDateIQ result = (AppSysOfflineDateIQ)collector.nextResult(5*1000);
		if(result != null && result.getError() == null){
			long offlineDate = result.getOfflineDate();
			return offlineDate;
		}else{
			return -1L;
		}
	}
	
	/**
	 * 发送短信
	 * @param message 消息内容
	 * @param phone 接收者号码
	 * @param participantJid 接收者jid
	 */
	public void sendSMS(Message message,String phone,String participantJid){
		smsContactSender = new SMSContact();
		String sender = SparkManager.getSessionManager().getUsername();
		String senderNick = SparkManager.getUserManager().getNickname();
		smsContactSender.setJid(sender);
		sms.setSender(smsContactSender);
		String content = senderNick+":"+message.getBody()+"[来自NETCALL消息,可直接回复]";
		sms.setContent(content);
		List<SMSContact> receivers = new ArrayList<SMSContact>();
		smsContactReceiver = new SMSContact();
		String nickName = StringUtilCommon.parseName(participantJid);
		smsContactReceiver.setName(nickName);
		smsContactReceiver.setPhone(phone);
		receivers.add(smsContactReceiver);
		sms.setReceivers(receivers);
		try {
			SMSManager.getInstance().sendSMS(sms,"reply");
		} catch (Exception e) {
			Log.error(e.getMessage(),e);
		}
	}

	@Override
	public void receivingMessage(Message message) {
		//do nothing
	}

	@Override
	public void closing() {
		chatRoomImpl.removeMessageEventListener(this);
		chatRoomImpl.removeClosingListener(this);
	}
	
	private void setAwayOfflineTime(){
		boolean isAllow = false;
		String isAllowFromServer = AppSysRes.getPropertyOnServer(AppSysRes.APP_SERVER_ISALLOW_CHANGE);
		if("true".equals(isAllowFromServer)){
			isAllow = true;
		}
		if(isAllow || isAllowFromServer == null){
			String awayTime = IntegrationManager.getSettingPreference().getPreferences().getAwayTime();
			String offlineTime = IntegrationManager.getSettingPreference().getPreferences().getOfflineTime();
			if(awayTime == null || "".equals(awayTime)){
				awayTime = "60";
			}
			if(offlineTime == null || "".equals(offlineTime)){
				offlineTime = "180";
			}
			try {
				ONEHOUR = Long.parseLong(awayTime)*60*1000;
				THREEHOUR = Long.parseLong(offlineTime)*60*1000;
			} catch (Exception e) {
				Log.error("离线离开时间转换异常"+e.getMessage());
			}
			//System.out.println("允许"+awayTime+"---"+offlineTime);
		}else{
			String awayTime = AppSysRes.getPropertyOnServer(AppSysRes.APP_SERVER_AWAY_TIME);
			String offlineTime = AppSysRes.getPropertyOnServer(AppSysRes.APP_SERVER_OFFLINE_TIME);
			try {
				ONEHOUR = Long.parseLong(awayTime)*60*1000;
				THREEHOUR = Long.parseLong(offlineTime)*60*1000;
			} catch (Exception e) {
				Log.error("离线离开时间转换异常"+e.getMessage());
			}
			//System.out.println("不允许"+awayTime+"---"+offlineTime);
		}
	}

}
